<template>
  <div>
    <el-button @click="exportClick()">导出表格</el-button>
    <el-table
      ref="report-table"
      :data="tableData"
      style="width: 100%"
      id="out-table"
    >
      <el-table-column prop="createTime" label="日期" width="180">
      </el-table-column>
      <el-table-column prop="tmName" label="姓名" width="180">
      </el-table-column>
      <el-table-column label="基础参数" align="center">
        <el-table-column prop="updateTime" label="地址"> </el-table-column>
        <el-table-column prop="updateTime" label="修改日期"> </el-table-column>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
// import { list } from "../../../api/test";
import FileSaver from "file-saver";
// import XLSXStyle from 'xlsx-style';
import * as XLSX from "xlsx";
export default {
  data() {
    return {
      tableData: [
        {
          createTime: "2024-6-10",
          tmName: "张三",
          updateTime: "2024-6-10",
          updateTime: "2024-6-10",
        },
        {
          createTime: "2024-6-10",
          tmName: "张三",
          updateTime: "2024-6-10",
          updateTime: "2024-6-10",
        },
        {
          createTime: "2024-6-10",
          tmName: "张三",
          updateTime: "2024-6-10",
          updateTime: "2024-6-10",
        },
        {
          createTime: "2024-6-10",
          tmName: "张三",
          updateTime: "2024-6-10",
          updateTime: "2024-6-10",
        },
      ],
      page: 1,
      limit: 10,
      total: 0,
      dataAll: [], //所有数据不影响原始数据
    };
  },
  mounted() {
    // this.query();
  },
  methods: {
    query(pagedta, limitdata) {
      this.exportExcel();
      // let page = 1;
      // let limit = 10;
      // if (pagedta) {
      //   page = pagedta;
      //   limit = limitdata;
      // } else {
      //   page = this.page;
      //   limit = this.limit;
      // }
      // list(page, limit).then((res) => {
      //   let { data } = res;
      //   if (pagedta) {
      //     this.dataAll = data.records;
      // this.exportExcel();
      //     this.exportTableExcel();
      //   } else {
      //     this.tableData = data.records;
      //     this.total = data.total;
      //   }
      // });
    },
    exportClick() {
      this.$confirm(
        "此操作将该项目下所有点集导出excel文件，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          console.log("导出excel");
          //如果不想影响表格的显示，可以重新调一次表格的接口
          //这里是全部导出数据赋值
          // this.form.pagesize = this.total;
          // //重新调用表格数据，也就是重新调用了页面加载表格显示数据
          // this.query(1, 10000);
          // this.getPigList();
          //调用成功后延迟加载导出
          this.exportExcel();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    exportExcel() {
      var that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require("../components/Export2Excel"); //刚刚新建Export2Excel.js文件的路径
        const tHeader = ["昵称", "姓名"]; //自定义列名
        const filterVal = ["createTime", "tmName"]; //这个也就是对应的字段名和列名一一对应上
        // const list = this.tableData; //table数据
        // console.log(list, '数据源');
        const data = that.formatJson(filterVal, this.tableData);
        console.log(data, "99999999999");
        export_json_to_excel(tHeader, data, "列表excel"); //导出文件名称
      });
    },
    formatJson(filterVal, jsonData) {
      //这个就是个过滤，在list中只要filterVal的数据，可以根据theader和filterVal进行个筛选
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    handleSizeChange(val) {
      this.limit = val;
      this.query();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.query();
    },
    exportTableExcel(excelName) {
      try {
        require.ensure([], () => {
          const {
            export_json_to_excel,
          } = require("../components/Export2Excel"); //刚刚新建Export2Excel.js文件的路径
          // const tHeader = ['昵称', '姓名']; //自定义列名
          const multiHeader = [["Id", "基本参数", "", "", "修改日期"]];
          const header = ["", "型号", "日期", "图片", ""];
          // 数据prop数据，用于遍历数据获取值
          const filterVal = [
            "id",
            "tmName",
            "createTime",
            "logoUrl",
            "updateTime",
          ];
          const merges = ["A1:A2", "B1:D1", "E1:E2"];
          // // const list = this.tableData; //table数据
          // // console.log(list, '数据源');
          // console.log(this.dataAll, '数据源');
          const data = this.formatJson(filterVal, this.dataAll);
          // const $e = this.$refs['report-table'].$el;
          // let $table = $e.querySelector('.el-table__fixed');
          // if (!$table) {
          //     $table = $e;
          // }
          export_json_to_excel({
            multiHeader,
            header,
            merges,
            data,
          });
          this.exportLoading = false;
        });

        // const wb = XLSX.utils.table_to_book($table, { raw: true });
        // this.setExlStyle(wb['Sheets']['Sheet1']);
        // // const wbout = XLSXStyle.write(wb, { bookType: 'xlsx', bookSST: true, type: 'buffer' });
        // /* 获取二进制字符串作为输出 */
        // var wbout = XLSX.write(wb, {
        //     bookType: 'xlsx',
        //     bookSST: true,
        //     type: 'array'
        // });
        // FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${excelName}.xlsx`);
      } catch (e) {
        if (typeof console !== "undefined") console.error(e);
      }
    },
    setExlStyle(data) {
      console.log(data, "data的值");
      // /*设置worksheet每列的最大宽度*/
      // const colWidth = data.map((row) =>
      //     row.map((val) => {
      //         /*先判断是否为null/undefined*/
      //         if (val == null) {
      //             return {
      //                 wch: 10
      //             };
      //         } else if (val.toString().charCodeAt(0) > 255) {
      //             /*再判断是否为中文*/
      //             return {
      //                 wch: val.toString().length * 2
      //             };
      //         } else {
      //             return {
      //                 wch: val.toString().length
      //             };
      //         }
      //     })
      // );
      // /*以第一行为初始值*/
      // let result = colWidth[0];
      // for (let i = 1; i < colWidth.length; i++) {
      //     for (let j = 0; j < colWidth[i].length; j++) {
      //         if (result[j]['wch'] < colWidth[i][j]['wch']) {
      //             result[j]['wch'] = colWidth[i][j]['wch'];
      //         }
      //     }
      // }
      // data['!cols'] = result;
      // return data;
      data["!cols"] = [];
      for (let key in data) {
        if (data[key] instanceof Object) {
          data[key].s = {
            alignment: {
              horizontal: "center",
              vertical: "center",
              wrapText: true,
            },
            font: {
              sz: 12, // 设置字号
              bold: true, // 是否加粗
            },
            numFmt: 0,
          };
          // // console.log(data[key].v, '这是什么');
          // let val = data[key].v;
          // // 根据需求设置列宽
          // // if (data['!cols'].length === 1) {
          // //     data['!cols'].push({ wpx: 120 });
          // // } else if (data['!cols'].length === 2) {
          // //     data['!cols'].push({ wpx: 280 });
          // // } else {
          // //     data['!cols'].push({ wpx: 45 });
          // // }
          // let colWidth = this.select(val);
          // data['!cols'].push(colWidth);
          // console.log(colWidth, '---------------------');
        }
      }
      console.log(data, "设置样式");
      return data;
    },
    select(val) {
      if (val == null) {
        return {
          wch: 10,
        };
      } else if (val.toString().charCodeAt(0) > 255) {
        /*再判断是否为中文*/
        return {
          wch: val.toString().length * 2,
        };
      } else {
        return {
          wch: val.toString().length,
        };
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
